@using Radzen.Blazor

<span class="rz-legend-item" style="@Style" @onclick="@OnClick" tabindex="0" @onkeypress="@OnKeyPress" @onkeypress:preventDefault=@preventKeyPress @onkeypress:stopPropagation>
    <svg width="@((MarkerSize * 2).ToInvariantString())" height="@((MarkerSize * 2).ToInvariantString())">
        <g class="rz-series-@Index @Class">
            <Marker X="@MarkerSize" Y="@MarkerSize" Type="@(MarkerType == MarkerType.None ? MarkerType.Square : MarkerType)" Fill="@Color" Size="@MarkerSize" />
        </g>
    </svg>
    <span class="rz-legend-item-text">@Text</span>
</span>

@code {
    [Parameter]
    public string Color { get; set; }

    [Parameter]
    public string Text { get; set; }

    [Parameter]
    public string Class { get; set;}

    [Parameter]
    public string Style { get; set; }

    [Parameter]
    public MarkerType MarkerType { get; set; }

    [Parameter]
    public double MarkerSize { get; set; }

    [Parameter]
    public EventCallback Click { get; set; }

    [Parameter]
    public bool Clickable { get; set; } = true;

    [Parameter]
    public int Index { get; set; }

    bool preventKeyPress = false;

    async Task OnClick()
    {
        if (Clickable)
        {
            await Click.InvokeAsync();
        }
    }

    async Task OnKeyPress(KeyboardEventArgs args)
    {
        var key = args.Code != null ? args.Code : args.Key;

        if (key == "Space" || key == "Enter")
        {
            preventKeyPress = true;

            await OnClick();
        }
        else
        {
            preventKeyPress = false;
        }
    }
}
